package com.innovation.sys.common.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.innovation.sys.common.vo.BaseException;

@RestControllerAdvice
public class GlobalExceptionHandler {

	private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(AuthenticationException.class)
	public JSONObject authenticationException(HttpServletResponse response, AuthenticationException ex) throws IOException {
		logger.error("异常信息为:{}" + ex.getMessage());
		return this.jsonObjWrapper(ex.getMessage(), 401, null);
	}

	@ExceptionHandler(AuthorizationException.class)
	public JSONObject authorizationException(HttpServletRequest reqest, HttpServletResponse response, Exception ex) {
		logger.error("异常信息为:{}" + ex.getMessage());
		return this.jsonObjWrapper(ex.getMessage(), 403, null);
	}

	@ExceptionHandler(BaseException.class)
	public JSONObject baseException(HttpServletResponse response, BaseException ex) throws IOException {
		logger.error("异常信息为:{}" + ex.getData());
		if (ex.getData().containsKey("message") && ex.getData().containsKey("code")) {
			String msg = ex.getData().get("message").toString();
			Integer code = StringUtils.stringToInteger(ex.getData().get("code").toString());
			return this.jsonObjWrapper(msg, code, null);
		}
		return this.jsonObjWrapper(ex.getMessage(), 601, null);
	}

	private JSONObject jsonObjWrapper(String msg, Integer code, Object data) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", msg);
		jsonObject.put("code", code);
		jsonObject.put("data", data);
		return jsonObject;
	}

//	@Override
//	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
//			Exception ex){
//		if(ex instanceof AuthenticationException) {
//			logger.error("异常信息为:{}" + ex.getMessage());
//		}else if(ex instanceof UnauthorizedException) {
//			logger.error("异常信息为:{}" + ex.getMessage());
//		}else if(ex instanceof BaseException) {
//			logger.error("异常信息为:{}" + ex.getMessage());
//		}
//		return null;
//	}

}
